/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SubsitemaAgenda;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import service.Usuario;

/**
 * Clase que cumple el objetivo de visualizar la agenda semanal
 * @author Mario
 */
public class Semana extends javax.swing.JPanel {

    private ArrayList<service.Cita> citas;
    public service.Usuario profesional;
    public service.HorarioProfesional horario;
    private Agenda agenda;        
    /*
     * Constructor de la clase, se inicializan los listeners y el array.
     */
    public Semana(service.Usuario profesional, Agenda agenda) {
        this.profesional = profesional;
        initComponents();       
        this.agenda = agenda;
        citas = new ArrayList<service.Cita>(); 
        refrescoAgenda();
        createPopupMenu();
    }
    /*
     * Agregan PanelCita al tabbedPane por cada paciente en el horario seleccionado
     * 
     */
    public void mostrarPanelCita(ArrayList<service.Cita> c){
        PanelCita panel;
        this.jTabbedPane1.removeAll();
        
        for(service.Cita a : c){
            service.Paciente p = (service.Paciente) cargarPaciente(a.getRutPaciente());
            panel = new PanelCita(a, agenda);
                    
             if(a.getEstado().equals("No Confirmada")){                
                this.jTabbedPane1.addTab(p.getNombres()+" "+p.getApellidoPaterno()+" "+p.getApellidoMaterno(), new ImageIcon(getClass().getResource("/GUI/Img/Estados/noconfirmada.png")), panel); 
             }
             if(a.getEstado().equals("Confirmada")){
                 this.jTabbedPane1.addTab(p.getNombres()+" "+p.getApellidoPaterno()+" "+p.getApellidoMaterno(), new ImageIcon(getClass().getResource("/GUI/Img/Estados/confirmada.png")), panel);             
             }
             if(a.getEstado().equals("No Pagada")){
                 this.jTabbedPane1.addTab(p.getNombres()+" "+p.getApellidoPaterno()+" "+p.getApellidoMaterno(), new ImageIcon(getClass().getResource("/GUI/Img/Estados/nopagada.png")), panel);                
             }
             if(a.getEstado().equals("Pagada")){
                 this.jTabbedPane1.addTab(p.getNombres()+" "+p.getApellidoPaterno()+" "+p.getApellidoMaterno(), new ImageIcon(getClass().getResource("/GUI/Img/Estados/pagada.png")), panel);                
             }
             if(a.getEstado().equals("Atendida")){
                 this.jTabbedPane1.addTab(p.getNombres()+" "+p.getApellidoPaterno()+" "+p.getApellidoMaterno(), new ImageIcon(getClass().getResource("/GUI/Img/Estados/atendida.png")), panel);                
             }
             if(a.getEstado().equals("No Atendida")){
                 this.jTabbedPane1.addTab(p.getNombres()+" "+p.getApellidoPaterno()+" "+p.getApellidoMaterno(), new ImageIcon(getClass().getResource("/GUI/Img/Estados/noatendida.png")), panel);                
             }
             if(a.getEstado().equals("Cancelada")){
                 this.jTabbedPane1.addTab(p.getNombres()+" "+p.getApellidoPaterno()+" "+p.getApellidoMaterno(), new ImageIcon(getClass().getResource("/GUI/Img/Estados/cancelada.png")), panel); 
             }       
    }
    }
    /*
     * Agrega una cita a la lista y se actualiza la tabla de citas.
     */
    public void addCita(service.Cita cita){
        this.citas.add(cita);
        updateTable(cita);
    }
   /*
    * Actualiza la lista de citas en la tabla
    */
    public void updateTable(service.Cita cita){

        TableModel model = this.jTable1.getModel();
           
        int y = this.jCalendar1.getCalendar().get(Calendar.DAY_OF_MONTH);
        Calendar nextDate = new GregorianCalendar();
        nextDate.setTime(jCalendar1.getDate());
        nextDate.add(Calendar.DAY_OF_MONTH, -y);        
        int posicion = 1;                
        while(!(nextDate.get(Calendar.DAY_OF_MONTH)==cita.getFecha().getDay())){
            nextDate.add(Calendar.DAY_OF_MONTH, 1);
            posicion++;               
        }                   
        int fila = -1;                        
        for(int i = 0 ; i<jTable1.getRowCount(); i++){
            int  hora = Integer.parseInt((((String) jTable1.getValueAt(i, 0)).split(":"))[0]);
            int  min = Integer.parseInt((((String) jTable1.getValueAt(i, 0)).split(":"))[1]);                        
            if(hora==cita.getDesdeHora() && min==cita.getDesdeMinuto())
                fila = i;                
        }        
        if(model.getValueAt(fila, posicion)!=null){
            ArrayList<service.Cita> c = (ArrayList)model.getValueAt(fila, posicion);
            c.add(cita);
            model.setValueAt(c, fila , posicion);
        }
        else {
            ArrayList<service.Cita> c = new ArrayList<service.Cita>();
            c.add(cita);
            model.setValueAt(c,fila, posicion);
        }
    }
    /*
     * Llena la tabla de citas de acuerdo a un dia seleccionado
     */
    public void llenarTabla(){        
        this.citas = new ArrayList<service.Cita>();
        limpiarTabla();
        obtenerCitasSemana();
        for(service.Cita c : this.citas){
            updateTable(c);
        }
        updateHorasBloqueadas();
    }
    public void updateHorasBloqueadas(){
        try {                        
            Calendar nextDate=new GregorianCalendar();              
            nextDate.setTime(jCalendar1.getCalendar().getTime());      
            int diaCalendar = jCalendar1.getCalendar().get(Calendar.DAY_OF_WEEK)-2;
            
            nextDate.add(Calendar.DAY_OF_MONTH, -diaCalendar);                                       
            Date desde = nextDate.getTime();
            nextDate.add(Calendar.DAY_OF_MONTH, 6);
            Date hasta = nextDate.getTime();            
            
            GregorianCalendar c = new GregorianCalendar();            
            c.setTime(desde);
            XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);  
            
            GregorianCalendar c2 = new GregorianCalendar();            
            c2.setTime(hasta);
            XMLGregorianCalendar calendar2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c2);            
            List<service.HoraBloqueada>horas = buscarHorasBloqueadas(calendar, calendar2, profesional.getRut());             
            for(int i = 0 ; i<horas.size() ; i++){
                String hora="", min="";
                if(horas.get(i).getHora()<10)
                    hora = "0"+horas.get(i).getHora();
                else
                    hora = horas.get(i).getHora()+"";
                if(horas.get(i).getMinuto()<10)
                    min = "0"+horas.get(i).getMinuto();
                else
                    min = horas.get(i).getMinuto()+"";      
                
                Calendar nextDate2 = new GregorianCalendar();
                nextDate2.setTime(desde);                                
                for(int j = 1 ; j<jTable1.getColumnCount(); j++){
                    for(int k = 0 ; k<jTable1.getRowCount();k++) {                        
                        if(jTable1.getValueAt(k, 0).equals(hora+":"+min) && horas.get(i).getFecha().getDay()==nextDate2.get(Calendar.DAY_OF_MONTH)){
                            jTable1.getModel().setValueAt(horas.get(i), k, j);                        
                        }
                    }
                    nextDate2.add(Calendar.DAY_OF_MONTH, 1);
                }                          
            }
        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(Dia.class.getName()).log(Level.SEVERE, null, ex);
        }                                               
    }
    /**
     * Limpia la tabla 
     */
    public void limpiarTabla(){
        for(int i = 0 ; i<this.jTable1.getRowCount() ; i++){
            for(int j = 1 ; j<this.jTable1.getColumnCount(); j++){            
                this.jTable1.getModel().setValueAt(null, i, j);
            }
        }
    }    
    /**
     * Obtiene citas de la semana seleccionada
     */
    public void obtenerCitasSemana(){
        try {
            Calendar nextDate=new GregorianCalendar();              
            nextDate.setTime(jCalendar1.getCalendar().getTime());      
            int diaCalendar = jCalendar1.getCalendar().get(Calendar.DAY_OF_WEEK)-2;
            
            nextDate.add(Calendar.DAY_OF_MONTH, -diaCalendar);                                       
            Date desde = nextDate.getTime();
            nextDate.add(Calendar.DAY_OF_MONTH, 6);
            Date hasta = nextDate.getTime();            
            
            GregorianCalendar c = new GregorianCalendar();            
            c.setTime(desde);
            XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);  
            
            GregorianCalendar c2 = new GregorianCalendar();            
            c2.setTime(hasta);
            XMLGregorianCalendar calendar2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c2);                        
                                  
            List<service.Cita> list = (List<service.Cita>) buscarCitasSemanaPorProfesional(calendar, calendar2, profesional.getRut());            
            for(int j = 0 ; j<list.size() ; j++){
                this.citas.add(list.get(j));
            }            
        }  catch (DatatypeConfigurationException ex) {
            Logger.getLogger(Semana.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public Usuario getProfesional() {
        return profesional;
    }
    public void setProfesional(Usuario profesional) {
        this.profesional = profesional;
        refrescoAgenda();
    }
    public void refrescoAgenda(){        
            verificoHorario();
            formatoTabla();
            llenarTabla();            
    }
    /*
     * 
     * Obtiene el mes desde el jcalendar con el formato adecuado
     */
    public String obtenerMes(){
        
        String fecha = "";
        int b = jCalendar1.getCalendar().get(Calendar.MONTH);
        
        if(b==0)
            fecha="enero";
        if(b==1)
            fecha="febrero";
        if(b==2)
            fecha="marzo";
        if(b==3)
            fecha="abril";
        if(b==4)
            fecha="mayo";
        if(b==5)
            fecha="junio";
        if(b==6)
            fecha="julio";
        if(b==7)
            fecha="agosto";
        if(b==8)
            fecha="septiembre";
        if(b==9)
            fecha="octubre";
        if(b==10)
            fecha="noviembre";
        if(b==11)
            fecha="diciembre";
       
        return fecha;
    }
    public void formatoTabla() {             
            int inicioHora = Integer.parseInt(horario.getHoraInicio()), inicioMin = Integer.parseInt(horario.getMinInicio()), terminoHora = Integer.parseInt(horario.getHoraTermino()), terminoMin = Integer.parseInt(horario.getMinTermino());
            int bloquesTotal = ((terminoHora-inicioHora)*60+(terminoMin- inicioMin))/horario.getDuracionBloque();
            Object[] o = new Object[8];
            DefaultTableModel model = new DefaultTableModel(){public boolean isCellEditable(int row, int column){return false;}};
            model.addColumn("Horario");
            model.addColumn("Lunes");model.addColumn("Martes");model.addColumn("Miércoles");model.addColumn("Jueves");
            model.addColumn("Viernes");model.addColumn("Sábado");model.addColumn("Domingo");
            
            for(int i = 0 ; i<bloquesTotal; i++){
                String hora="", min="";
                if(inicioHora<10)
                    hora = "0"+inicioHora;           
                else
                    hora = ""+inicioHora;
                if(inicioMin<10)
                    min = "0"+inicioMin;
                else
                    min = ""+inicioMin;
                
                o[0] = hora+":"+min; o[1] = ""; o[2] = ""; o[3] = ""; o[4] = ""; o[5] = ""; o[6] = ""; o[7] = ""; 
                                
                model.addRow(o);
                if(inicioMin<60)
                    inicioMin+=horario.getDuracionBloque();
                if(inicioMin==60){
                    inicioMin = 0;
                    inicioHora+=1;
                }
                if(inicioMin>60){
                    inicioMin = inicioMin-60;
                    inicioHora+=1;
                }
            }        
            this.jTable1.setModel(model);                            
            this.jTable1.getColumnModel().getColumn(0).setMaxWidth(200);
            this.jTable1.getColumnModel().getColumn(1).setCellRenderer(new RendererCellSemana());
            this.jTable1.getColumnModel().getColumn(2).setCellRenderer(new RendererCellSemana());
            this.jTable1.getColumnModel().getColumn(3).setCellRenderer(new RendererCellSemana());
            this.jTable1.getColumnModel().getColumn(4).setCellRenderer(new RendererCellSemana());
            this.jTable1.getColumnModel().getColumn(5).setCellRenderer(new RendererCellSemana());
            this.jTable1.getColumnModel().getColumn(6).setCellRenderer(new RendererCellSemana());
            this.jTable1.getColumnModel().getColumn(7).setCellRenderer(new RendererCellSemana());               
            this.jTable1.setRowHeight(20);        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jCalendar1 = new com.toedter.calendar.JCalendar();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTabbedPane1 = new javax.swing.JTabbedPane();

        setBackground(new java.awt.Color(255, 255, 255));

        jCalendar1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jCalendar1PropertyChange(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"8:00", null, null, null, null, null, null, null},
                {"9:00", null, null, null, null, null, null, null},
                {"10:00", null, null, null, null, null, null, null},
                {"11:00", null, null, null, null, null, null, null},
                {"12:00", null, null, null, null, null, null, null},
                {"13:00", null, null, null, null, null, null, null},
                {"14:00", null, null, null, null, null, null, null},
                {"15:00", null, null, null, null, null, null, null},
                {"16:00", null, null, null, null, null, null, null},
                {"17:00", null, null, null, null, null, null, null},
                {"18:00", null, null, null, null, null, null, null},
                {"19:00", null, null, null, null, null, null, null}
            },
            new String [] {
                "Horario", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setAutoscrolls(false);
        jTable1.setCellSelectionEnabled(true);
        jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTable1.setFocusCycleRoot(true);
        jTable1.setRowHeight(20);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jCalendar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 610, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(284, Short.MAX_VALUE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(13, 13, 13)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addComponent(jCalendar1, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE))
                    .addContainerGap(193, Short.MAX_VALUE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getClickCount() == 1 && jTable1.getSelectedColumn() !=0 && !evt.isConsumed()) {
            Object o = jTable1.getModel().getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn());
            if( o instanceof ArrayList) {
                mostrarPanelCita((ArrayList)o);
            }                    
            else
                jTabbedPane1.removeAll();
        } 
    }//GEN-LAST:event_jTable1MouseClicked

    private void jCalendar1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jCalendar1PropertyChange
        jTabbedPane1.removeAll();
        refrescoAgenda();
    }//GEN-LAST:event_jCalendar1PropertyChange
    public void verificoHorario(){        
        try {
            GregorianCalendar c = new GregorianCalendar();            
            c.setTime(jCalendar1.getDate());
            XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
            this.horario = (service.HorarioProfesional) cargarHorarioSegunFecha(calendar, profesional.getRut());            
        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(Dia.class.getName()).log(Level.SEVERE, null, ex);
        }                
    }
    private void createPopupMenu() {
        JPopupMenu popup = new JPopupMenu();
        JMenuItem bloquear = new JMenuItem("bloquear hora");        
        bloquear.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/candado-cerrado.png")));
        JMenuItem desbloquear = new JMenuItem("desbloquear hora");
        desbloquear.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/candado-abierto.png")));
        popup.add(bloquear);
        popup.add(desbloquear);   
        MouseListener popupListener = new PopupListener(popup);
        jTable1.addMouseListener(popupListener);
        bloquear.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae) {
                if(jTable1.getSelectedRow()!=-1){
                    if(!(jTable1.getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn()) instanceof ArrayList)){
                        try {
                            service.HoraBloqueada h = new service.HoraBloqueada();
                            h.setRutProfesional(profesional.getRut());
                            int  hora = Integer.parseInt((((String) jTable1.getValueAt(jTable1.getSelectedRow(), 0)).split(":"))[0]);
                            int  min = Integer.parseInt((((String) jTable1.getValueAt(jTable1.getSelectedRow(), 0)).split(":"))[1]); 
                            h.setHora(hora);
                            h.setMinuto(min);                                            
                            Calendar nextDate=new GregorianCalendar();  

                            nextDate.setTime(jCalendar1.getDate());
                            while(nextDate.get(Calendar.DAY_OF_WEEK)!=2)//lunes  
                                nextDate.add(Calendar.DAY_OF_MONTH, -1);                              
                            while(nextDate.get(Calendar.DAY_OF_WEEK)!=jTable1.getSelectedColumn()+1)
                               nextDate.add(Calendar.DAY_OF_MONTH, 1);                                                                         
                            GregorianCalendar c = new GregorianCalendar();           
                            c.setTime(nextDate.getTime());
                            XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);                                              
                            h.setFecha(calendar);
                            agregarHoraABloquear(h);
                            jTable1.getModel().setValueAt(h, jTable1.getSelectedRow(), jTable1.getSelectedColumn());
                        } catch (DatatypeConfigurationException ex) {
                            Logger.getLogger(Dia.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    else {
                        JOptionPane.showMessageDialog(agenda,"Existen citas en este horario, no es posible bloquearlo");                        
                    }
                }
            }
        });
        desbloquear.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                if(jTable1.getSelectedRow()!=-1 && jTable1.getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn()) instanceof service.HoraBloqueada){
                    eliminarHoraBloqueada((service.HoraBloqueada)jTable1.getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn()));
                    jTable1.getModel().setValueAt(null, jTable1.getSelectedRow(), jTable1.getSelectedColumn());
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public com.toedter.calendar.JCalendar jCalendar1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTabbedPane jTabbedPane1;
    public javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
private class PopupListener extends MouseAdapter {

        private JPopupMenu popup;

        PopupListener(JPopupMenu popupMenu) {
            popup = popupMenu;
        }
        @Override
        public void mousePressed(MouseEvent e) {            
            maybeShowPopup(e);                        
        }
        @Override
        public void mouseReleased(MouseEvent e) {
            JTable source = (JTable)e.getSource();
            int row = source.rowAtPoint( e.getPoint() );
            int column = source.columnAtPoint( e.getPoint() );            
            source.changeSelection(row, column, false, false);
            if (jTable1.getSelectedRow() != -1 && jTable1.getSelectedColumn() != 0) {
                maybeShowPopup(e);
            }
        }
        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {                                
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }

    class RendererCellSemana implements TableCellRenderer  
{  
    JTextPane textPane;  
   
    public RendererCellSemana()  
    {  
        textPane = new JTextPane();  
       
    }  
   
    @Override
    public Component getTableCellRendererComponent(JTable table,  
                                                   Object value,  
                                                   boolean isSelected,  
                                                   boolean hasFocus,  
                                                   int row, int column)  
    {  

        boolean isFuera = true;
        this.textPane= new JTextPane();                 
        Gson gson = new Gson();
        String json = horario.getDisponibilidad();        
        ArrayList<Point> dis = gson.fromJson(json, new TypeToken<ArrayList<Point>>(){}.getType());
        for(Point p : dis){
            if (p.equals(new Point(row, column))){
                this.textPane.setBackground(new Color(173,216,230));        
                isFuera = false;
            }
        }
        if(isSelected) 
            this.textPane.setBackground(Color.cyan);
        
        if(value instanceof ArrayList){
            ArrayList<service.Cita> a = (ArrayList)value;
            for(int i = 0 ; i<a.size() ; i++){
                JLabel label = new JLabel();
                label.setText(" ");               
                agregarEstado(a.get(i), label);
                if(isFuera){
                    this.textPane.setBackground(Color.red);
                    agenda.cambiarEtiquetaMensajeria("Existen citas fuera del horario disponible", Color.red);
                    
                }
                textPane.insertComponent(label);
            }                       
        }           
        if(value instanceof service.HoraBloqueada){
            textPane.setBackground(Color.ORANGE);
        }
        if(isSelected) 
            this.textPane.setBackground(Color.cyan);
        return textPane;
    }  
    public void agregarEstado(service.Cita cita, JLabel label){
        
        
        if(cita.getEstado().equals("No Confirmada")){                
                label.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/Estados/noconfirmada.png")));   
                
            }
        if(cita.getEstado().equals("Confirmada")){
               label.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/Estados/confirmada.png")));
               
            }
        if(cita.getEstado().equals("No Pagada")){
               label.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/Estados/nopagada.png")));
               
        }
        if(cita.getEstado().equals("Pagada")){
               label.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/Estados/pagada.png")));
               
        }
        if(cita.getEstado().equals("Atendida")){
               label.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/Estados/atendida.png")));
               
        }
        if(cita.getEstado().equals("No Atendida")){
               label.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/Estados/noatendida.png")));
               
        }
        if(cita.getEstado().equals("Cancelada")){
               label.setIcon(new ImageIcon(getClass().getResource("/GUI/Img/Estados/cancelada.png")));
               
            }                           
    }
}

    private static Object cargarPaciente(java.lang.String rut) {
        service.PacienteWS_Service service = new service.PacienteWS_Service();
        service.PacienteWS port = service.getPacienteWSPort();
        return port.cargarPaciente(rut);
    }

    private static Object cargarHorarioSegunFecha(javax.xml.datatype.XMLGregorianCalendar fecha, java.lang.String rut) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.cargarHorarioSegunFecha(fecha, rut);
    }

    private static boolean agregarHoraABloquear(service.HoraBloqueada hora) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.agregarHoraABloquear(hora);
    }

    private static boolean eliminarHoraBloqueada(service.HoraBloqueada hora) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.eliminarHoraBloqueada(hora);
    }

    private static java.util.List<service.HoraBloqueada> buscarHorasBloqueadas(javax.xml.datatype.XMLGregorianCalendar fechaDesde, javax.xml.datatype.XMLGregorianCalendar fechaHasta, java.lang.String rut) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.buscarHorasBloqueadas(fechaDesde, fechaHasta, rut);
    }    

    private static Object buscarCitasSemanaPorProfesional(javax.xml.datatype.XMLGregorianCalendar fechaInicio, javax.xml.datatype.XMLGregorianCalendar fechaTermino, java.lang.String rut) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.buscarCitasSemanaPorProfesional(fechaInicio, fechaTermino, rut);
    }
    
}
